<template>
  <div class="employees-container">
    <el-card class="employees-card">
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
        </div>
      </template>

      <el-form :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="姓名/工号"
            clearable
          />
        </el-form-item>
        <el-form-item label="部门" style="width: 250px;">
          <el-tree-select
            v-model="searchForm.departmentId"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择部门"
            clearable
          />
        </el-form-item>
        <el-form-item label="岗位" style="width: 250px;">
          <el-select v-model="searchForm.positionId" placeholder="请选择岗位" clearable>
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" style="width: 150px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
            <el-option label="试用期" value="probation" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="employeeList" style="width: 100%" v-loading="loading">
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="入职时间">{{ row.joinDate }}</el-descriptions-item>
              <el-descriptions-item label="工作年限">{{ row.workYears }}年</el-descriptions-item>
              <el-descriptions-item label="学历">{{ row.education }}</el-descriptions-item>
              <el-descriptions-item label="毕业院校">{{ row.school }}</el-descriptions-item>
              <el-descriptions-item label="专业">{{ row.major }}</el-descriptions-item>
              <el-descriptions-item label="毕业年份">{{ row.graduationYear }}</el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="employeeId" label="工号" width="100" />
        <el-table-column prop="name" label="姓名" width="100">
          <template #default="{ row }">
            <el-avatar :size="24" :src="row.avatar" class="avatar" />
            <span class="name">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="departmentId" label="部门">
          <template #default="{ row }">
            {{ getDepartmentName(row.departmentId) }}
          </template>
        </el-table-column>
        <el-table-column prop="positionId" label="岗位">
          <template #default="{ row }">
            {{ getPositionName(row.positionId) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="职级" width="80">
          <template #default="{ row }">
            <el-tag>{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-dropdown>
              <el-button type="primary" link>更多<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleTransfer(row)">调岗</el-dropdown-item>
                  <el-dropdown-item @click="handleLeave(row)">离职</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { getEmployeePage } from '@/api/employees'
import { getDepartmentList } from '@/api/departments'
import { getPositionList } from '@/api/positions'

interface Employee {
  id: number
  employeeId: string
  name: string
  avatar: string
  department: string
  departmentId: number
  position: string
  positionId: number
  level: string
  phone: string
  email: string
  status: 'active' | 'inactive' | 'probation'
  joinDate: string
  workYears: number
  education: string
  school: string
  major: string
  graduationYear: string
}

interface Department {
  id: number
  name: string
  children?: Department[]
}

interface Position {
  id: number
  name: string
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  keyword: '',
  departmentId: null as number | null,
  positionId: null as number | null,
  status: ''
})

const employeeList = ref<Employee[]>([])
const departmentOptions = ref<Department[]>([])
const positionOptions = ref<Position[]>([])

function getStatusType(status: string) {
  const map: Record<string, string> = {
    active: 'success',
    inactive: 'danger',
    probation: 'warning'
  }
  return map[status] || 'info'
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    active: '在职',
    inactive: '离职',
    probation: '试用期'
  }
  return map[status] || '未知'
}

// 通过岗位ID获取岗位名称
function getPositionName(positionId: number): string {
  const position = positionOptions.value.find(p => p.id === positionId)
  return position ? position.name : '未知岗位'
}

// 通过部门ID获取部门名称
function getDepartmentName(departmentId: number): string {
  const findDepartment = (departments: Department[], id: number): Department | undefined => {
    for (const dept of departments) {
      if (dept.id === id) return dept
      if (dept.children) {
        const found = findDepartment(dept.children, id)
        if (found) return found
      }
    }
    return undefined
  }
  
  const department = findDepartment(departmentOptions.value, departmentId)
  return department ? department.name : '未知部门'
}

async function loadEmployees() {
  loading.value = true
  try {
    const response = await getEmployeePage({
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.keyword,
      departmentId: searchForm.departmentId,
      positionId: searchForm.positionId,
      status: searchForm.status
    })
    employeeList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取员工列表失败')
    console.error('获取员工列表失败:', error)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadEmployees()
}

function handleReset() {
  Object.assign(searchForm, {
    keyword: '',
    departmentId: null,
    positionId: null,
    status: ''
  })
  handleSearch()
}

function handleAdd() {
  // TODO: 实现新增员工功能
  ElMessage.info('新增员工功能开发中')
}

function handleEdit(row: Employee) {
  // TODO: 实现编辑员工功能
  ElMessage.info('编辑员工功能开发中')
}

function handleDetail(row: Employee) {
  // TODO: 实现查看员工详情功能
  ElMessage.info('查看员工详情功能开发中')
}

function handleTransfer(row: Employee) {
  // TODO: 实现员工调岗功能
  ElMessage.info('员工调岗功能开发中')
}

function handleLeave(row: Employee) {
  ElMessageBox.confirm(
    '确定要将该员工设置为离职状态吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // TODO: 实现员工离职功能
      ElMessage.success('操作成功')
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadEmployees()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadEmployees()
}

// 将平铺的部门数据转换为树形结构
function buildDepartmentTree(departments: any[]): any[] {
  const departmentMap = new Map()
  const tree: any[] = []
  
  // 首先将所有部门存入map
  departments.forEach(dept => {
    departmentMap.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树形结构
  departments.forEach(dept => {
    const node = departmentMap.get(dept.id)
    if (dept.parentId) {
      const parent = departmentMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    } else {
      tree.push(node)
    }
  })
  
  return tree
}

// 加载部门数据
async function loadDepartments() {
  try {
    const response = await getDepartmentList()
    departmentOptions.value = buildDepartmentTree(response)
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

async function loadPositions() {
  try {
    const response = await getPositionList()
    positionOptions.value = response
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  }
}

onMounted(() => {
  // 初始加载
  loadDepartments()
  loadPositions()
  // 初始加载
  loadEmployees()
})

</script>

<style scoped>
.employees-container {
  padding: 20px;
}

.employees-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar {
  margin-right: 8px;
  vertical-align: middle;
}

.name {
  vertical-align: middle;
}
</style>